package site.edody.dframe.admin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.model.TreeNode;
import org.ssssssss.magicapi.core.service.MagicResourceService;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 启动后检查初始化
 */
@Order(2)
@Component
public class ApiAutoConfig  implements ApplicationRunner {

    private static final String DFRAME = "dframe";
    private static final String ADMINPATH = "/system";
    private static final String SCRIPTRESOURCE = "dframescript.zip";
    private final Logger log = LoggerFactory.getLogger(ApiAutoConfig.class);

    @Autowired
    MagicResourceService service;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        if (service.tree() == null || service.tree().get("api") == null ){
            log.info("应用未有接口，将进行初始化导入.......");
            initScript(true);
        } else if  (service.tree().get("api").getChildren() == null ||  service.tree().get("api").getChildren().size() <=0){
            log.info("admin 未有接口，将进行初始化导入.......");
            initScript(true);
        } else {
            List<TreeNode<Group>> dframenode = getNodesByName(service.tree().get("api").getChildren(),DFRAME);
            if ( dframenode!= null){ //已经 存在节点
                if (log.isDebugEnabled()){
                    for (TreeNode<Group> tmp :dframenode){
                        log.debug(tmp.toString());
                    }
                }
                log.info("admin 初始化操作，存在dframe 节点，继续确认是否已经初始化完成....");
                List<TreeNode<Group>> adminnode = getNodesByPath(dframenode,ADMINPATH);
                if ( adminnode != null){
                    log.info("admin 脚本已经存在，无需操作");
                } else{ //不存在脚本
                    initScript(true);
                }
            } else { // 不存在dframe 节点，继续初始化
                log.info("admin 需要初始化脚本，且系统已经存在脚本,可能覆盖...");
                initScript(true);
            }
        }

    }

    /**
     *
     * @param nodes
     * @param path
     * @return
     */
    private List<TreeNode<Group>> getNodesByPath(List<TreeNode<Group>> nodes,String path){
        AtomicReference<List<TreeNode<Group>>> rs = new AtomicReference<>();
        nodes.iterator().forEachRemaining((node) -> {
            if (path.equals(node.getNode().getPath())){
                rs.set(node.getChildren());
            }
        });
        return rs.get();
    }
    /**
     * 根据节点名称获取资源
     * @param nodes
     * @param nodename
     * @return
     */
    private List<TreeNode<Group>> getNodesByName(List<TreeNode<Group>> nodes,String nodename){
        AtomicReference<List<TreeNode<Group>>> rs = new AtomicReference<>();
        nodes.iterator().forEachRemaining((node) -> {
            if (nodename.equals(node.getNode().getName())){
                rs.set(node.getChildren());
            }
        });
        return rs.get();
    }

    /**
     *
     * @param isfull
     * @throws Exception
     */
    private void initScript(boolean isfull) throws Exception {
        // 初始化操作

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(SCRIPTRESOURCE);
        boolean upload = service.upload(inputStream, isfull);
        if (!upload){
            throw new Exception("加载初始脚本异常");
        }
    }
}
